<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="工单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择工单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.WORK_ORDER)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="工单ID" align="center" prop="id" />
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="技术员ID" align="center" prop="technicianId" />
      <el-table-column label="工单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.WORK_ORDER" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-dropdown>
            <el-button link type="primary">
              更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="scope.row.status === 1"
                  @click="handleAcceptOrder(scope.row)"
                >
                  接单
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 2"
                  @click="handleCompleteOrder(scope.row)"
                >
                  完成工单
                </el-dropdown-item>
                <el-dropdown-item @click="handleViewDetail(scope.row)">
                  查看详情
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <WorkOrderForm ref="formRef" @success="getList" />

  <!-- 工单详情弹窗 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="工单详情"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-descriptions :column="2" border>
      <el-descriptions-item label="工单ID">{{ selectedWorkOrder?.id }}</el-descriptions-item>
      <el-descriptions-item label="订单ID">{{ selectedWorkOrder?.orderId }}</el-descriptions-item>
      <el-descriptions-item label="技术员ID">{{ selectedWorkOrder?.technicianId }}</el-descriptions-item>
      <el-descriptions-item label="工单状态">
        <dict-tag :type="DICT_TYPE.WORK_ORDER" :value="selectedWorkOrder?.status" />
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ selectedWorkOrder?.createTime ? formatDate(selectedWorkOrder.createTime) : '-' }}
      </el-descriptions-item>
    </el-descriptions>

    <el-divider>订单信息</el-divider>

    <el-descriptions :column="2" border>
      <el-descriptions-item label="套餐名称">{{ selectedOrder?.packageName }}</el-descriptions-item>
      <el-descriptions-item label="宽带速率">{{ selectedOrder?.speed }}</el-descriptions-item>
      <el-descriptions-item label="订单金额">
        <span class="text-red-500">¥{{ selectedOrder?.totalPrice }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="订单状态">
        <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="selectedOrder?.status" />
      </el-descriptions-item>
      <el-descriptions-item label="收货信息" :span="2">
        {{ selectedOrder?.addressInfo || '-' }}
      </el-descriptions-item>
    </el-descriptions>

    <template #footer>
      <el-button @click="detailDialogVisible = false">关 闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { WorkOrderApi, WorkOrderVO } from '@/api/workOrder'
import { OrderApi, OrderVO } from '@/api/order'
import { PointsApi } from '@/api/points'
import WorkOrderForm from './WorkOrderForm.vue'
import { ArrowDown } from '@element-plus/icons-vue'

/** 工单信息 列表 */
defineOptions({ name: 'WorkOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<WorkOrderVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const detailDialogVisible = ref(false)
const selectedWorkOrder = ref<WorkOrderVO>()
const selectedOrder = ref<OrderVO>()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await WorkOrderApi.getWorkOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await WorkOrderApi.deleteWorkOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await WorkOrderApi.exportWorkOrder(queryParams)
    download.excel(data, '工单信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 查看工单详情 */
const handleViewDetail = async (row: WorkOrderVO) => {
  try {
    // 获取工单详情
    selectedWorkOrder.value = row
    // 获取订单详情
    selectedOrder.value = await OrderApi.getOrder(row.orderId)
    // 打开弹窗
    detailDialogVisible.value = true
  } catch (error) {
    message.error('获取详情失败')
  }
}

/** 格式化日期 */
const formatDate = (timestamp: number) => {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

/** 接单 */
const handleAcceptOrder = async (row: WorkOrderVO) => {
  try {
    // 更新工单状态为已接单
    await WorkOrderApi.updateWorkOrder({
      id: row.id!,
      status: 2 // 已接单状态
    })
    message.success('接单成功')
    // 刷新列表
    getList()
  } catch (error) {
    message.error('接单失败')
  }
}

/** 完成工单 */
const handleCompleteOrder = async (row: WorkOrderVO) => {
  try {
    // 更新工单状态为已完成
    await WorkOrderApi.updateWorkOrder({
      id: row.id!,
      status: 3 // 已完成状态
    })
    
    // 更新订单状态为已完成
    const now = new Date()
    const formattedDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`
    
    await OrderApi.updateOrder({
      id: row.orderId,
      status: 4, // 已完成状态
      payTime: formattedDate
    })

    // 更新用户信息
    await PointsApi.updateByOrder(row.orderId)
    
    message.success('工单已完成')
    // 刷新列表
    getList()
  } catch (error) {
    message.error('操作失败')
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
